﻿using System;
using NHibernate;
using c = NHibernate.Cfg;
using NHibernate.Criterion;

namespace OrmSmackdown.NHibernate
{
    public class Crud : ICrud
    {
        ISessionFactory _sessionFactory;
        ISession _session;

        public Crud()
        {
            try
            {
            c.Configuration _configuration = new c.Configuration();
            _configuration.AddAssembly("OrmSmackdown");
            _sessionFactory = _configuration.BuildSessionFactory();
            _session = _sessionFactory.OpenSession();
            }
            catch(Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message);
                throw;
            }

        }

        public int Create(string firstName, string lastName, string email)
        {
            var contact1 = new NHibernate.Contact { FirstName = firstName, LastName = lastName, Email = email };

            _session.Save(contact1);

            return contact1.PersonId;
        }

        public IPerson Read(int id)
        {
            var person = (IPerson)_session.CreateCriteria(typeof(Person))
                .Add(Expression.Eq("PersonId", id)).UniqueResult();

            return person;
        }

        public void Update(int id, string firstName, string lastName, string email)
        {
            var person = (IPerson)_session.CreateCriteria(typeof(Person))
                .Add(Expression.Eq("PersonId", id)).UniqueResult();

            person.FirstName = firstName;
            person.LastName = lastName;
            person.Email = email;

            _session.Update(person);

            _session.Flush();
        }

        public void Delete(int id)
        {
            var person = (IPerson)_session.CreateCriteria(typeof(Person))
                .Add(Expression.Eq("PersonId", id)).UniqueResult();

            _session.Delete(person);

            _session.Flush();
        }

        public void Dispose()
        {
            _session.Dispose();
            _sessionFactory.Dispose();
        }
    }
}
